<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>视频会话</title>
    <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.3.0/weui.min.css"/>
    <link rel="stylesheet" href="css/index.css"/>
    <link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<textarea id="tvArea" class="left-float-record-window" readonly></textarea>
<div class="left-float-contact-parent-window">
    <div class="contact-title">通讯录</div>
    <div id="contactArea"  class="left-float-contact-window">
        <!--<a class="contact-item" href="javascript:">你好啊</a>-->
    </div>
</div>
<div id="remoteArea" style="display: none" class="right-float-window2">
    <!--<video id="remoteView" style="display: none" class="item-video" autoplay=""></video>-->
</div>
<div class="app-location"
     style="border-radius: 10px;
                margin-top: 50px">
    <div class="main-video-parent">
        <video id="localView" class="main-video" autoplay=""></video>
    </div>

    <div class="weui-form__control-area">
        <div class="weui-cells__group weui-cells__group_form">
            <div class="weui-cells weui-cells_form">
                <div class="weui-cell weui-cell_active">
                    <div class="weui-cell__hd"><label class="weui-label">用户号码</label></div>
                    <div class="weui-cell__bd">
                        <input id="nickName" class="weui-input" placeholder="请填写或者选择用户号码"/>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="weui-flex">
        <div class="weui-flex__item">
            <a id="close" href="javascript:" class="weui-btn weui-btn_warn"><img src="images/cut_call.png" class="center-icon-20"/>取消</a>
        </div>
        <div class="weui-flex__item">
            <a id="submit" href="javascript:" class="weui-btn weui-btn_primary"><img src="images/make_call.png" class="center-icon-20"/>呼叫</a>
        </div>
    </div>
    <div id="moreCall" style="display: none" class="more-call">多呼</div>

</div>


<div class="js_dialog" id="androidDialog2" style="display: none;">
    <div class="weui-mask"></div>
    <div class="weui-dialog weui-skin_android">
        <div id="dialog_text" class="weui-dialog__bd">
            提示信息
        </div>
        <div class="weui-dialog__ft">
            <a id="btnClose" href="javascript:" class="weui-dialog__btn weui-dialog__btn_default">辅助操作</a>
            <a id="btnSure" href="javascript:" class="weui-dialog__btn weui-dialog__btn_primary">主操作</a>
        </div>
    </div>
</div>
<div id="loadingToast" style="display: none;">
    <div class="weui-mask_transparent"></div>
    <div class="weui-toast">
        <i class="weui-loading weui-icon_toast"></i>
        <!--<p id="toast_text" class="weui-toast__content">数据加载中</p>-->
    </div>
</div>

<script language=javascript src='https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'></script>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="https://res.wx.qq.com/open/libs/weuijs/1.2.1/weui.min.js"></script>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>-->
<script src='js/socket.io.js'></script>
<script language=javascript src='js/http.js'></script>
<script language=javascript src='js/md5.js'></script>
<script language=javascript src='js/RTC.js'></script>
<script language=javascript src='js/socketConnect.js'></script>
<script type="text/javascript">
    const localVideo=document.getElementById('localView');
    const tvarea=$('#tvArea');
    const nickName=$('#nickName');
    const remoteArea=$('#remoteArea');
    const contactArea=$('#contactArea');

    const remoteVideoView={};
    const remoteAudioView={};
    const remoteVideos={};
    const remoteAudios={};
    //呼叫类型0单呼，1多呼
    let callType=0;
    //通讯录
    let sysContacts=null;
    //多呼呼叫对象
    let callPeos=[];
    //本地流
    let localStream=null;
    let localAudioStream=null;
    //用户信息
    let user={};
    user['id']='123410';
    user['name']='蒋大师';
    user['sex']=0;
    //房间名
    let room_name;
    /**
     * 音视频配置
     * @type {{video: boolean, audio: boolean}}
     */
    const config={
        video: true,
        audio: true
    };
    function alart(msg,submit,callBack) {
        $('#dialog_text').html(msg);
        $('#btnSure').html(submit);
        $('#btnClose').hide();
        $('#btnSure').off('click').on('click',function () {
            $('#androidDialog2').fadeOut(200);
            callBack();
        });
        $('#androidDialog2').fadeIn(200);
    }

    function alartClose(msg,close,closeBack,submit,callBack) {
        $('#dialog_text').html(msg);
        $('#btnSure').html(submit);
        $('#btnClose').show();
        $('#btnClose').html(close);
        $('#btnClose').off('click').on('click',function (event) {
            $('#androidDialog2').fadeOut(200);
            closeBack();
        });
        $('#btnSure').off('click').on('click',function (event) {
            $('#androidDialog2').fadeOut(200);
            callBack();
        });
        $('#androidDialog2').fadeIn(200);
    }

    function loading(){
        if ($('#loadingToast').css('display') != 'none') return;
        $('#loadingToast').fadeIn(100);
    }

    function dismiss() {
        if ($('#loadingToast').css('display') == 'none') return;
        $('#loadingToast').fadeOut(100);
    }

    function chooseContacts(view) {
        for(key in sysContacts){
            let item=document.getElementById('user_'+key);
            if(view.id!='user_'+user['id']){
                if(view.id==item.id){
                    if(item.className=='contact-item'){
                        callPeos[callPeos.length]=key;
                        item.className='contact-item-active';
                    }else{
                        callPeos.remove(key);
                        item.className='contact-item';
                    }
                }
            }else{
                alart('不能选自己哟','好的',function () {

                });
            }
        }
        if(callPeos.length==1){
            nickName.val(callPeos[0]);
        }else if(callPeos.length==0){
            nickName.val('');
        }else{
            nickName.val(callPeos);
        }
    }

    function refreshContacts() {
        let position=0;
        for(it=0;it<callPeos.length;it++){
            if(sysContacts[callPeos[it]]==null){
                callPeos.remove(callPeos[it]);
            }
        }
        for(key in sysContacts){

            let className='';
            if(callPeos.includes(key)){
                className='contact-item-active';
            }else{
                className='contact-item';
            }

            let item='<a id="user_'+key+'" class="'+className+'" href="javascript:" onclick="chooseContacts(this)">'+sysContacts[key]['name']+'</a>';
            if(position==0){
                contactArea.html(contactArea.innerHTML=item);
            }else{
                contactArea.html(contactArea.innerHTML+=item);
            }
            position++;
        }

        if(callPeos.length==1){
            nickName.val(callPeos[0]);
        }else if(callPeos.length==0){
            nickName.val('');
        }else{
            nickName.val(callPeos);
        }
    }


    //访问用户媒体设备的兼容方法
    function getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
            //最新的标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints,success, error)
        } else if (navigator.mozGetUserMedia) {
            //firfox浏览器
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constraints, success, error);
        }
    }

    function success(stream) {
        localStream=stream;
        //兼容webkit核心浏览器
        console.log("本地",stream);
        localVideo.srcObject = stream;
        // try {
        //     window.AudioContext = window.AudioContext || window.webkitAudioContext;
        //     let audioCtx = new AudioContext();
        //     // localAudioStream=window.audioContext
        //     let source=audioCtx.createMediaStreamSource(stream);
        //     let biquadFilter=audioCtx.createBiquadFilter();
        //     biquadFilter.type="lowshelf";
        //     biquadFilter.frequency.value=1000;
        //     biquadFilter.gain.value=25;
        //     source.connect(biquadFilter);
        //     biquadFilter.connect(audioCtx.destination);
        // } catch (e) {
        //     alert('Web Audio API not supported.');
        // }

    }

    function error(err){
        console.log(err.toString());
    }

    function getStream(){
        if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
            //调用用户媒体设备, 访问摄像头
            getUserMedia(config, success, error);
        } else {
            alert('不支持访问用户媒体');
        }
    }

    // function touchStream(view) {
    //     if(view.srcObject==localStream){
    //         localVideo.srcObject=localStream;
    //         view.srcObject=remoteVideos[view.tag];
    //     }else{
    //         localVideo.srcObject=remoteVideos[view.tag];
    //         view.srcObject=localStream;
    //     }
    // }

    function addVideo(uid,stream) {
        let remoteView=remoteVideoView[uid];
        let remoteAudio=remoteAudioView[uid];
        if(remoteView==null){
            remoteView='remote_'+uid;
            let item='<video id="'+remoteView+'" tag="'+uid+'" class="item-video" autoplay=""></video>';
            let isEmpty=true;
            if(JSON.stringify(remoteVideoView)!=JSON.stringify({})){
                isEmpty=false;
            }
            if(isEmpty){
                remoteArea.fadeIn(100);
                remoteArea.html(remoteArea.innerHTML=item);
            }else{
                remoteArea.html(remoteArea.innerHTML+=item);
            }
            remoteVideoView[uid]=remoteView;
        }

        if(remoteAudio==null){
            remoteAudio='remote_audio_'+uid;
            let item='<video id="'+remoteView+'" tag="'+uid+'" class="item-video" autoplay="" style="display: none"></video>';
            let isEmpty=true;
            if(JSON.stringify(remoteAudioView)!=JSON.stringify({})){
                isEmpty=false;
            }
            if(isEmpty){
                remoteArea.fadeIn(100);
                remoteArea.html(remoteArea.innerHTML=item);
            }else{
                remoteArea.html(remoteArea.innerHTML+=item);
            }
            remoteAudioView[uid]=remoteAudio;
        }

        if(stream.getTracks()[0].kind=='audio'){
            remoteAudios[uid]=stream;
        }
        if(stream.getTracks()[0].kind=='video'){
            remoteVideos[uid]=stream;
        }

        for(key in remoteVideoView){
            let video=remoteVideos[key];
            let view=document.getElementById(remoteVideoView[key]);

            if(video!=null){
                view.srcObject=video;
            }

        }
        for(key in remoteAudioView){
            let audio=remoteAudios[key];
            let view=document.getElementById(remoteAudioView[key]);

            if(audio!=null){
                view.srcObject=audio;
            }
        }
    }

    function removeSelf(uid) {
        console.log('当前已有的视图2',remoteVideoView);
        if(uid!=null){
            let view=document.getElementById(remoteVideoView[uid]);
            view.parentNode.removeChild(view);
            delete remoteVideoView[uid];
            if(JSON.stringify(remoteVideoView)==JSON.stringify({})){
                remoteArea.fadeOut(100);
            }
        }else{
            for(let key in remoteVideoView){
                let view=document.getElementById(remoteVideoView[key]);
                view.parentNode.removeChild(view);
                delete remoteVideoView[key];
            }
            remoteArea.fadeOut(100);
        }
    }

    function setRecords(data) {
        let msg=tvarea.val();
        msg=msg+"["+new Date().Format("yyyy-MM-dd hh:mm:ss")+"]"+data+"\n";
        tvarea.val(msg);
        tvarea.scrollTop(tvarea[0].scrollHeight);
    }

    function open(){
        // socket.connect('http://funnymudpee.qicp.vip',user,function (contacts) {
        socket.connect('https://www.linziblog.cn',user,function (contacts) {
        // socket.connect('https://localhost',user,function (contacts) {
            sysContacts=contacts;
            for(let key in contacts){
                setRecords(key+"上线。");
            }
            refreshContacts();
        },function message(data) {
            let fromid=data['from'];
            let sdp=data['sdp'];
            let candidate=data['candidate'];
            if(data['type']=='offer'){
                rtc.responseOffer(localStream,fromid,sdp);
                rtc.createAnswer(fromid,function asn(answer) {
                    socket.sendSDP(answer,user['id'],fromid);
                });
            }else if(data['type']=='answer'){
                rtc.responseAnswer(fromid,sdp);
            }else if(data['type']=='candidate'){
                rtc.responseIceDate(fromid,data['id'],data['label'],candidate);
            }
        },function beSingleCall(data) {
            let fromUser=data['from'];
            room_name=data['room'];
            alartClose("用户"+fromUser['name']+"请求与你通话，是否接受？","挂断",function () {
                socket.refuseCall(room_name,user['id'],fromUser['id']);
            },"接听",function () {

                rtc.init(fromUser['id'],function iceCall(ice) {
                    socket.sendIceData(ice,user['id'],fromUser['id']);
                },function trackBack(event) {
                    addVideo(fromUser['id'],event.stream);
                });

                socket.intoRoom(room_name,user['id']);
            });
        },function beMoreCall(data) {
            let fromUser=data['from'];
            room_name=data['room'];

            alartClose("用户"+fromUser['name']+"邀请你加入多人会话，是否接受？","拒绝",function () {

            },"加入",function () {

                rtc.init(fromUser['id'],function iceCall(ice) {
                    socket.sendIceData(ice,user['id'],fromUser['id']);
                },function trackBack(event) {
                    addVideo(fromUser['id'],event.stream);
                });
                socket.intoMoreRoom(room_name,user['id']);
            });
        },function getRoom(data) {
            room_name = data;
            if(callType==0){
                socket.intoRoom(room_name,user['id']);
            }else{
                socket.intoMoreRoom(room_name,user['id']);
            }
        },function create() {
            if(callType==0) {
                socket.singleCall(room_name, user['id'], nickName.val());
            }else{
                socket.moreCall(room_name,user['id'],callPeos);
            }
        },function join(joindata) {
            dismiss();

            rtc.init(joindata,function iceCall(ice) {
                socket.sendIceData(ice,user['id'],joindata);
            },function trackBack(event) {
                console.log("网络流2",event.stream);
                addVideo(joindata,event.stream);
            });

            rtc.createOffer(localStream,joindata,function offerCreate(offer) {
                console.log(offer);
                socket.sendSDP(offer,user['id'],joindata);
            });
        },function beRefuse(refuseData) {
            setRecords("用户" + refuseData['from'] + "拒绝了你的邀请");
            socket.outRoom(room_name, user['id']);
            dismiss();
            alart("用户" + refuseData['from'] + "拒绝了你的邀请", "确定", function () {

            });
        },function someBodyOut(data) {
            rtc.close(data);
            if(callType==0){
                socket.outRoom(room_name,user['id']);
                alart("用户"+data+"结束了通话","确定",function () {

                });
                setRecords("用户"+data+"结束了通话");
            }else{
                setRecords("用户"+data+"离开了房间");
            }
            removeSelf(data);
        },function userBuse(uid) {
            alart("用户"+uid+"忙碌","确定",function () {

            });
            dismiss();
        },function someBodyCalled(data) {
            setRecords("用户"+data['from']['id']+"呼叫过你\n");
            dismiss();
        });
    }

    $(function () {
        getStream();
        open();

        $('#submit').unbind('click').click(function () {
            if(callPeos.length==0){
                alart('请选择呼叫对象','确定');
                return;
            }
            loading();
            if(callPeos.length==1){
                callType=0;
                nickName.val(callPeos[0]);
            }else{
                callType=1;
            }
            socket.getRoom(user['id']);
        });

        $('#close').unbind('click').click(function () {
            socket.outRoom(room_name,user['id']);
            rtc.close();
            removeSelf();
        });
        $('#moreCall').unbind('click').click(function () {
            loading();
            callType=1;
            // callPeos.length=0;
            // for(key in sysContacts){
            //     if(key!=user['id']){
            //         callPeos[callPeos.length]=key;
            //     }
            // }
            socket.getRoom(user['id']);
        });

    });
    window.onbeforeunload=function () {
        socket.close();
    };
</script>
</body>
</html>